package com.centaline.androidsalesblog.activities.sale;

import android.content.Intent;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.bumptech.glide.DrawableRequestBuilder;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.map.AroundMapActivity;
import com.centaline.androidsalesblog.api.sale.SchoolDetailApi;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.businissobject.SchoolBo;
import com.centaline.androidsalesblog.model.businissobject.SchoolToEstateBo;
import com.centaline.androidsalesblog.model.responseobject.SchoolDetailRo;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.centaline.androidsalesblog.utils.BdMapUtil;
import com.centaline.androidsalesblog.utils.ContactUtil;
import com.centaline.androidsalesblog.utils.ResponseCheck;
import com.centaline.androidsalesblog.utils.TextFormatUtil;
import com.centaline.androidsalesblog.widgets.dropdown.SpecialLoadView;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.widget.AbstractSpecialLoadView;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.Locale;

import rx.functions.Action1;

/**
 * 学校详情
 */
public class SchoolDetailActivity extends BaseActivity implements View.OnClickListener {

    private SpecialLoadView specialLoadView;
    private ImageView img_cover, img_arrow_address, img_map;
    private AppCompatTextView atv_title_ad, atv_school_type, atv_school_feature, atv_tel,
            atv_school_sale, atv_address, atv_map_name, atv_nav;
    private RelativeLayout rl_phone, rl_school_to_sale, rl_map;

    private int schoolId;
    private SchoolBo schoolBo;
    private SchoolDetailApi schoolDetailApi;
    private DrawableRequestBuilder<String> requestBuilder;
    private LocationClient locationClient;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_school_detail;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        specialLoadView = (SpecialLoadView) findViewById(R.id.specialLoadView);
        img_cover = (ImageView) findViewById(R.id.img_cover);
        atv_title_ad = (AppCompatTextView) findViewById(R.id.atv_title_ad);
        atv_school_type = (AppCompatTextView) findViewById(R.id.atv_school_type);
        atv_school_feature = (AppCompatTextView) findViewById(R.id.atv_school_feature);
        atv_tel = (AppCompatTextView) findViewById(R.id.atv_tel);
        atv_school_sale = (AppCompatTextView) findViewById(R.id.atv_school_sale);
        atv_address = (AppCompatTextView) findViewById(R.id.atv_address);
        atv_nav = (AppCompatTextView) findViewById(R.id.atv_nav);
        atv_map_name = (AppCompatTextView) findViewById(R.id.atv_map_name);
        img_arrow_address = (ImageView) findViewById(R.id.img_arrow_address);
        img_map = (ImageView) findViewById(R.id.img_map);
        rl_phone = (RelativeLayout) findViewById(R.id.rl_phone);
        rl_school_to_sale = (RelativeLayout) findViewById(R.id.rl_school_to_sale);
        rl_map = (RelativeLayout) findViewById(R.id.rl_map);
    }

    @Override
    protected void initViews() {
        requestBuilder = GlideLoad.init(this);
        specialLoadView.setLoadStatusListener(new AbstractSpecialLoadView.LoadStatusListener() {
            @Override
            public void load() {
                request();
            }
        });

        schoolDetailApi = new SchoolDetailApi(SchoolDetailActivity.class, SchoolDetailRo.class, new IResponseListener<SchoolDetailRo>() {
            @Override
            public void onResponse(SchoolDetailRo schoolDetailRo) {
                if (ResponseCheck.check(schoolDetailRo)) {
                    specialLoadView.loadSuccess();
                    schoolBo = schoolDetailRo.getSchoolBo();
                    setData();
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                specialLoadView.loadError();
            }
        });
        schoolId = getIntent().getIntExtra(ExtraConstant.SchoolId, 0);
        schoolDetailApi.setSchoolId(schoolId);

        locationClient = MyLocation.getLocationClient();
        RxMap.location(locationClient, false)
                .compose(this.<BDLocation>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        cancelLoadingDialog();
                        switch (bdLocation.getLocType()) {
                            case 61:
                            case 161:
                                NaviParaOption naviParaOption = new NaviParaOption();
                                naviParaOption.startPoint(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()))
                                        .endPoint(new LatLng(schoolBo.getLat(),
                                                schoolBo.getLng()));
                                BaiduMapNavigation.openBaiduMapNavi(naviParaOption, SchoolDetailActivity.this);
                                break;
                            default:
                                snack("定位失败");
                                break;
                        }
                    }
                });
        atv_nav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
            }
        });

        request();
    }

    private void request() {
        schoolDetailApi.startRequest();
    }

    private void setData() {
        final SchoolToEstateBo schoolToEstateBo = schoolBo.getSchoolToEstateBo();
        atv_title_ad.setText(schoolBo.getSchoolShortName());
        GlideLoad.load(new GlideLoad.Builder(requestBuilder, schoolBo.getDefaultImg())
                .placeHolder(R.drawable.ic_default_est_estate)
                .error(R.drawable.ic_default_est_estate)
                .openWifiSwitch()
                .into(img_cover));
        TextFormatUtil.setText(atv_school_type, schoolBo.getSchoolGrade());
        TextFormatUtil.setText(atv_school_feature, schoolBo.getSchoolFeature());
        TextFormatUtil.setText(atv_tel, schoolBo.getSchoolTel());
        rl_phone.setVisibility(TextUtils.isEmpty(schoolBo.getSchoolTel()) ? View.GONE : View.VISIBLE);
        rl_school_to_sale.setVisibility(schoolBo.getSchoolToEstateBo() == null ||
                schoolBo.getSchoolToEstateBo().getSchoolEstateInfoBos() == null ? View.GONE : View.VISIBLE);
        if (TextUtils.isEmpty(schoolBo.getRegion()) ||
                TextUtils.isEmpty(schoolBo.getGscope())) {
            atv_address.setText(String.format("%s%s  %s", schoolBo.getRegion(), schoolBo.getGscope(), schoolBo.getAddress()));
        } else {
            atv_address.setText(String.format("%s-%s  %s", schoolBo.getRegion(), schoolBo.getGscope(), schoolBo.getAddress()));
        }


        atv_school_sale.setText(schoolToEstateBo == null ?
                "暂无" : String.format(Locale.CHINA, "%.0f元/平  %d套在售",
                schoolBo.getAvgPrice(), schoolBo.getSchoolSPostNum()));

        atv_map_name.setText(schoolBo.getSchoolShortName());
        if (schoolBo.getLat() != 0 &&
                schoolBo.getLng() != 0) {
            img_arrow_address.setVisibility(View.VISIBLE);
            atv_nav.setVisibility(View.VISIBLE);
            rl_map.setVisibility(View.VISIBLE);
            GlideLoad.load(new GlideLoad.Builder(requestBuilder,
                    BdMapUtil.getBaiduMapImgUrl(schoolBo.getLng(), schoolBo.getLat()))
                    .placeHolder(R.drawable.ic_banner)
                    .error(R.drawable.ic_banner)
                    .openWifiSwitch()
                    .into(img_map));
        }
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        showLoadingDialog();
        locationClient.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_phone:
                ContactUtil.dial(this, schoolBo.getSchoolTel());
                baiduEvent("H2_1_Click");
                break;
            case R.id.rl_school_to_sale:
                if (schoolBo.getSchoolToEstateBo() != null &&
                        schoolBo.getSchoolToEstateBo().getSchoolEstateInfoBos() != null) {
                    startActivity(new Intent(this, SchoolToSaleListActivity.class)
                            .putExtra(ExtraConstant.SchoolId, String.valueOf(schoolId))
                            .putExtra(ExtraConstant.SchoolShortName, schoolBo.getSchoolShortName())
                            .putExtra(SchoolToSaleListActivity.SchoolToEsfList,
                                    schoolBo.getSchoolToEstateBo().getSchoolEstateInfoBos()));
                }
                baiduEvent("H2_2_Click");
                break;
            case R.id.rl_address://地图
            case R.id.img_map:
                if (schoolBo == null ||
                        schoolBo.getLat() == 0 || schoolBo.getLng() == 0) {
                    snack("地理位置获取失败");
                } else {
                    startActivity(new Intent(this, AroundMapActivity.class)
                            .putExtra(ExtraConstant.LatLng, new LatLng(schoolBo.getLat(), schoolBo.getLng()))
                            .putExtra(ExtraConstant.MAP_NAME, schoolBo.getSchoolShortName()));
                }
                break;
            default:
                break;
        }
    }
}
